package com.user.manage.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class DigestUtils {

    private static String MD5_ALGORITHM = "MD5";
    private static String SHA_256_ALGORITHM = "SHA-256";

    public static MessageDigest getDigest(String algorithm) {
        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        return digest;
    }


    public static byte[] digest(String algorithm, String data) {
        MessageDigest digest = getDigest(algorithm);
        digest.update(data.getBytes());
        return digest.digest();
    }

    public static String digestHex(String algorithm, String data) {
        byte[] digest = digest(algorithm, data);
        return encodeHexStr(digest);
    }

    private static String encodeHexStr(byte[] digest) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : digest) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }


    public static String md5(String data) {
        return digestHex(MD5_ALGORITHM, data);
    }

    public static String sha256(String data) {
        return digestHex(SHA_256_ALGORITHM, data);
    }

    public static String generateToken(String data) {
        String randomString = StringUtil.getRandomString(5);
        return sha256(data + randomString);
    }

    public static void main(String[] args) {
        System.out.println(DigestUtils.sha256("admin"));
        System.out.println(DigestUtils.sha256("admin1"));
        System.out.println(DigestUtils.sha256("user"));
    }

}